<template>
	<view class="comments-section">
		<view class="comments-header">
			<text class="comments-title">评论 {{ commentCount }}</text>
		</view>

		<!-- 评论列表 -->
		<view class="comment-list">
			<template v-for="comment in rootComments" :key="comment.id">
				<!-- 主评论 -->
				<view class="comment-item main-comment">
					<image class="comment-avatar" :src="comment.userAvatar"
						@click="handleToUser(comment.commenterUserId)" mode="aspectFill"></image>
					<view class="comment-content">
						<view class="comment-header">
							<text class="comment-user"
								@click="handleToUser(comment.commenterUserId)">{{ comment.userName }}</text>
							<text class="comment-time">{{ formatTime(comment.createdTime) }}</text>
						</view>
						<text class="comment-text">{{ comment.commentContent }}</text>
						<view class="comment-actions">
							<view class="comment-like" @click="handleLikeComment(comment)">
								<uni-icons :type="comment.isLiked ? 'heart-filled' : 'heart'"
									:color="comment.isLiked ? '#ff4757' : '#666'" size="14"></uni-icons>
								<text class="like-count" v-if="comment.likeCount > 0">{{ comment.likeCount }}</text>
							</view>
							<text class="reply-btn" @click="handleReplyComment(comment)">回复</text>
						</view>
					</view>
				</view>

				<!-- 子评论/回复 -->
				<view class="reply-list" v-if="comment.replies && comment.replies.length > 0">
					<view class="reply-item" v-for="reply in comment.replies" :key="reply.id">
						<image class="reply-avatar" :src="reply.userAvatar" @click="handleToUser(reply.commenterUserId)"
							mode="aspectFill"></image>
						<view class="reply-content">
							<view class="reply-header">
								<text class="reply-user"
									@click="handleToUser(reply.commenterUserId)">{{ reply.userName }}</text>
								<text class="reply-time">{{ formatTime(reply.createdTime) }}</text>
							</view>
							<view class="reply-text-wrapper">
								<!-- 如果有回复目标用户，显示@用户名 -->
								<text class="reply-target" v-if="reply.replyToUserName">
									@{{ reply.replyToUserName }}
								</text>
								<text class="reply-text">{{ reply.commentContent }}</text>
							</view>
							<view class="reply-actions">
								<view class="reply-like" @click="handleLikeComment(reply)">
									<uni-icons :type="reply.isLiked ? 'heart-filled' : 'heart'"
										:color="reply.isLiked ? '#ff4757' : '#666'" size="12"></uni-icons>
									<text class="like-count" v-if="reply.likeCount > 0">{{ reply.likeCount }}</text>
								</view>
								<text class="reply-btn" @click="handleReplyToReply(comment, reply)">回复</text>
							</view>
						</view>
					</view>

					<!-- 展开/收起更多回复 -->
					<view class="more-replies" v-if="comment.totalReplies > comment.replies.length"
						@click="loadMoreReplies(comment)">
						<text class="more-replies-text">
							展开{{ comment.totalReplies - comment.replies.length }}条回复
						</text>
						<uni-icons type="down" size="12" color="#666"></uni-icons>
					</view>
				</view>
			</template>
		</view>

		<!-- 空状态 -->
		<view class="empty-comments" v-if="commentList.length === 0 && !loading">
			<text class="empty-text">还没有评论，快来抢沙发吧~</text>
		</view>

		<!-- 加载状态 -->
		<view class="loading-comments" v-if="loading">
			<text class="loading-text">评论加载中...</text>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { ref, computed, defineProps, defineEmits, onMounted } from 'vue'
	import { getCommentsByPostId, addPostComment, toggleCommentLike, getUserCommentLikedByPostId } from '@/api/post/comment/comment'
	import { getUserInfoByUserId } from '@/api/user/user'
	import type { PostCommentInfo } from '@/api/post/comment/comment'
	import useUserStore from '@/store/modules/user'

	// 直接使用 userStore，保持响应式
	const userStore = useUserStore()

	// 扩展评论类型，添加用户信息和层级关系
	interface CommentWithUserInfo extends PostCommentInfo {
		userName ?: string;
		userAvatar ?: string;
		isLiked ?: boolean;
		replies ?: CommentWithUserInfo[];
		totalReplies ?: number;
		replyToUserName ?: string;
	}

	// Props 定义
	const props = defineProps<{
		postId : number;
	}>()

	// Events 定义
	const emit = defineEmits<{
		commentCountChange : [count: number];
		replyComment : [comment: CommentWithUserInfo, parentComment?: CommentWithUserInfo]; // 新增
		toUser : [userId: number];
	}>()

	// 评论相关数据
	const commentList = ref<CommentWithUserInfo[]>([])
	const commentCount = ref(0)
	const loading = ref(false)
	const userLikedCommentIds = ref<Set<string>>(new Set()) // 新增：用户点赞过的评论ID集合

	// 新增：获取用户点赞过的评论ID列表
	const getUserLikedComments = async (postId: number) => {
		try {
			// 检查用户是否登录
			if (!userStore.user || !userStore.user.userId) {
				userLikedCommentIds.value = new Set()
				return
			}

			const res = await getUserCommentLikedByPostId(postId, userStore.user.userId)
			if (res.code === 200 && res.data && Array.isArray(res.data)) {
				// 将点赞过的评论ID存储到Set中，便于快速查找
				userLikedCommentIds.value = new Set(res.data.map(id => id.toString()))
				console.log('用户点赞过的评论ID:', Array.from(userLikedCommentIds.value))
			} else {
				userLikedCommentIds.value = new Set()
			}
		} catch (error) {
			console.error('获取用户点赞状态失败:', error)
			userLikedCommentIds.value = new Set()
		}
	}

	// 计算根评论（没有父评论的评论）
	const rootComments = computed(() => {
		return commentList.value.filter(comment => !comment.parentCommentId)
	})

	// 构建评论树结构
	const buildCommentTree = async (comments : CommentWithUserInfo[]) : Promise<CommentWithUserInfo[]> => {
		const commentMap = new Map<string, CommentWithUserInfo>()
		const rootComments : CommentWithUserInfo[] = []

		// 初始化所有评论，添加replies数组
		comments.forEach(comment => {
			comment.replies = []
			commentMap.set(comment.id.toString(), comment)
		})

		// 构建树结构
		for (const comment of comments) {
			if (comment.parentCommentId) {
				// 这是一个回复
				const parentComment = commentMap.get(comment.parentCommentId.toString())
				if (parentComment) {
					// 如果有回复目标用户ID，调用API获取用户名
					if (comment.replyToUserId) {
						try {
							const userRes = await getUserInfoByUserId(Number(comment.replyToUserId))
							if (userRes.code === 200 && userRes.data) {
								comment.replyToUserName = userRes.data.nickName || userRes.data.userName || `用户${comment.replyToUserId}`
							} else {
								comment.replyToUserName = `用户${comment.replyToUserId}`
							}
						} catch (error) {
							console.warn('获取回复目标用户信息失败:', error)
							comment.replyToUserName = `用户${comment.replyToUserId}`
						}
					}
					parentComment.replies!.push(comment)
					parentComment.totalReplies = (parentComment.totalReplies || 0) + 1
				}
			} else {
				// 这是根评论
				rootComments.push(comment)
			}
		}

		return rootComments
	}

	// 获取评论数据
	const getComments = async (postId : number, page : number = 1, reset : boolean = false) => {
		try {
			loading.value = true
			
			// 先获取用户点赞状态
			await getUserLikedComments(postId)
			
			// 修改：使用一个很大的pageSize来获取所有评论
			const res = await getCommentsByPostId(postId, 1, 9999)
	
			if (res.rows && Array.isArray(res.rows)) {
				// 处理评论数据，添加用户信息
				const processedComments : CommentWithUserInfo[] = await Promise.all(
					res.rows.map(async (comment : PostCommentInfo) => {
						let userName = comment.createdBy || `用户${comment.commenterUserId}`
						let userAvatar = ''
	
						// 根据commenterUserId获取用户信息
						if (comment.commenterUserId) {
							try {
								const userRes = await getUserInfoByUserId(Number(comment.commenterUserId))
								if (userRes.code === 200 && userRes.data) {
									userName = userRes.data.nickName || userRes.data.userName || userName
									userAvatar = userRes.data.avatar || userAvatar
								}
							} catch (error) {
								console.warn('获取用户信息失败:', error)
							}
						}
	
						return {
							...comment,
							userName,
							userAvatar,
							// 修改：根据用户点赞状态设置isLiked
							isLiked: userLikedCommentIds.value.has(comment.id.toString()),
							likeCount: Number(comment.likeCount || 0),
							replies: [],
							totalReplies: 0
						}
					})
				)
	
				// 修改：总是重置评论列表，不再追加
				commentList.value = processedComments
	
				// 构建评论树结构
				const treeComments = await buildCommentTree(commentList.value)
				commentList.value = treeComments
	
				commentCount.value = res.total || 0
	
				emit('commentCountChange', commentCount.value)
			} else {
				commentList.value = []
				commentCount.value = 0
			}
		} catch (error) {
			console.error('获取评论失败:', error)
			uni.showToast({
				title: '获取评论失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 格式化时间
	// 格式化时间
	const formatTime = (timeStr : string) : string => {
		if (!timeStr) return ''

		const time = new Date(timeStr)

		// 检查日期是否有效
		if (isNaN(time.getTime())) {
			return '时间格式错误'
		}

		const now = new Date()
		const diff = now.getTime() - time.getTime()

		// 如果时间是未来时间，显示具体时间
		if (diff < 0) {
			return time.toLocaleString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit'
			})
		}

		const seconds = Math.floor(diff / 1000)
		const minutes = Math.floor(diff / (1000 * 60))
		const hours = Math.floor(diff / (1000 * 60 * 60))
		const days = Math.floor(diff / (1000 * 60 * 60 * 24))

		if (seconds < 60) {
			return '刚刚'
		} else if (minutes < 60) {
			return `${minutes}分钟前`
		} else if (hours < 24) {
			return `${hours}小时前`
		} else if (days < 7) {
			return `${days}天前`
		} else {
			return time.toLocaleString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit'
			})
		}
	}

	// 点赞评论
	// 点赞评论
	const handleLikeComment = async (comment : CommentWithUserInfo) => {
	try {
	// 调用点赞评论API
	await toggleCommentLike(comment.id)
	
	// API调用成功后更新本地状态
	comment.isLiked = !comment.isLiked
	
	// 同步更新用户点赞状态集合
	if (comment.isLiked) {
	userLikedCommentIds.value.add(comment.id.toString())
	// 确保数值运算：先转换为数字再相加
	comment.likeCount = Number(comment.likeCount || 0) + 1
	uni.showToast({
	title: '点赞成功',
	icon: 'success'
	})
	} else {
	userLikedCommentIds.value.delete(comment.id.toString())
	// 确保数值运算：先转换为数字再相减
	comment.likeCount = Math.max(0, Number(comment.likeCount || 0) - 1)
	uni.showToast({
	title: '取消点赞',
	icon: 'success'
	})
	}
	} catch (error) {
	console.error('点赞评论失败:', error)
	uni.showToast({
	title: '操作失败',
	icon: 'error'
	})
	}
	}

	// 回复主评论
	const handleReplyComment = (comment : CommentWithUserInfo) => {
		// 通知父组件打开回复弹窗
		emit('replyComment', comment)
	}

	// 回复子评论
	const handleReplyToReply = (mainComment : CommentWithUserInfo, replyComment : CommentWithUserInfo) => {
		emit('replyComment', replyComment, mainComment)
	}

	const handleToUser = (userId : number) => {
		emit('toUser', userId)
	}

	// 添加新的方法供父组件调用
	const addReply = async (parentCommentId : string, newReply : CommentWithUserInfo) => {
		try {
			// 获取当前用户信息
			const userStore = useUserStore()

			// 构建回复数据
			const replyData : PostCommentInfo = {
				id: '',
				commentCode: newReply.commentCode,
				postId: newReply.postId,
				commenterUserId: userStore.user.userId || newReply.commenterUserId,
				parentCommentId: parentCommentId,
				replyToUserId: newReply.replyToUserId,
				commentContent: newReply.commentContent,
				likeCount: 0,
				isDraft: 0,
				aiAuditStatus: 0,
				aiAuditReason: null,
				aiAuditTime: null,
				createdBy: userStore.user.nickName || userStore.user.userName || newReply.createdBy,
				createdTime: new Date().toISOString(),
				updatedBy: null,
				updatedTime: new Date().toISOString(),
				deletedFlag: 0
			}

			// 调用API添加回复
			const response = await addPostComment(replyData)

			if (response.code === 200) {
				// 找到父评论并添加回复
				const parentComment = commentList.value.find(c => c.id === parentCommentId)
				if (parentComment) {
					if (!parentComment.replies) {
						parentComment.replies = []
					}

					// 使用正确的用户信息构造回复对象
					const reply : CommentWithUserInfo = {
						...replyData,
						id: response.data?.id || Date.now().toString(),
						createdTime: response.data?.createdTime || replyData.createdTime,
						userName: userStore.user.nickName || userStore.user.userName || '用户',
						userAvatar: userStore.user.avatar || '/static/images/profile.jpg',
						isLiked: false,
						replies: [],
						totalReplies: 0,
						replyToUserName: newReply.replyToUserName
					}

					parentComment.replies.push(reply)
					parentComment.totalReplies = (parentComment.totalReplies || 0) + 1
					commentCount.value++
					emit('commentCountChange', commentCount.value)
				}

				uni.showToast({
					title: '回复发布成功',
					icon: 'success'
				})
			} else {
				throw new Error(response.msg || '回复发布失败')
			}
		} catch (error) {
			console.error('添加回复失败:', error)
			uni.showToast({
				title: '回复发布失败',
				icon: 'error'
			})
		}
	}

	// 加载更多回复
	const loadMoreReplies = async (comment : CommentWithUserInfo) => {
		// TODO: 实现加载更多回复的逻辑
		console.log('加载更多回复:', comment)
	}

	// 刷新评论列表
	const refreshComments = async () => {
		// 重新获取用户点赞状态和评论列表
		await getComments(props.postId, 1, true)
	}

	// 添加新评论到列表
	const addComment = async (newComment : Partial<CommentWithUserInfo>) => {
		try {
			// 获取当前时间，确保格式一致
			const currentTime = new Date().toISOString()

			// 构建评论数据
			const commentData : PostCommentInfo = {
				id: '',
				commentCode: `C${Date.now()}`,
				postId: props.postId.toString(),
				commenterUserId: userStore.user.userId || '',
				parentCommentId: null,
				replyToUserId: null,
				commentContent: newComment.commentContent || '',
				likeCount: 0,
				isDraft: 0,
				aiAuditStatus: 0,
				aiAuditReason: null,
				aiAuditTime: null,
				createdBy: userStore.user.nickName || userStore.user.userName || '',
				createdTime: currentTime,
				updatedBy: null,
				updatedTime: currentTime,
				deletedFlag: 0
			}

			// 调用API添加评论
			const response = await addPostComment(commentData)

			if (response.code === 200) {
				// API调用成功，添加到本地列表
				const comment : CommentWithUserInfo = {
					...commentData,
					id: response.data?.id || Date.now().toString(),
					// 使用API返回的时间，如果没有则使用本地时间
					createdTime: response.data?.createdTime || currentTime,
					userName: userStore.user.nickName || userStore.user.userName || '用户',
					userAvatar: userStore.user.avatar || '/static/images/profile.jpg',
					isLiked: false,
					replies: [],
					totalReplies: 0
				}

				commentList.value.unshift(comment)
				commentCount.value++
				emit('commentCountChange', commentCount.value)

				uni.showToast({
					title: '评论发布成功',
					icon: 'success'
				})
			} else {
				throw new Error(response.msg || '评论发布失败')
			}
		} catch (error) {
			console.error('添加评论失败:', error)
			uni.showToast({
				title: '评论发布失败',
				icon: 'error'
			})
		}
	}

	// 暴露方法给父组件调用
	defineExpose({
		refreshComments,
		addComment,
		addReply
	})

	// 组件挂载时加载评论
	onMounted(() => {
		getComments(props.postId, 1, true)
	})
</script>

<style lang="scss" scoped>
	.comments-section {
		border-top: 20rpx solid #f8f8f8;
		padding: 32rpx;
		padding-bottom: 60rpx;

		.comments-header {
			margin-bottom: 32rpx;

			.comments-title {
				font-size: 30rpx;
				font-weight: 600;
				color: #333;
			}
		}

		.comment-list {
			.main-comment {
				margin-bottom: 24rpx;
			}
		}

		.comment-item {
			display: flex;
			margin-bottom: 32rpx;

			.comment-avatar {
				width: 64rpx;
				height: 64rpx;
				border-radius: 50%;
				margin-right: 24rpx;
				flex-shrink: 0;
			}

			.comment-content {
				flex: 1;

				.comment-header {
					display: flex;
					align-items: center;
					margin-bottom: 8rpx;

					.comment-user {
						font-size: 24rpx;
						color: #666;
						margin-right: 16rpx;
						font-weight: 500;
					}

					.comment-time {
						font-size: 22rpx;
						color: #999;
					}
				}

				.comment-text {
					font-size: 28rpx;
					color: #333;
					line-height: 1.5;
					margin-bottom: 16rpx;
					display: block;
				}

				.comment-actions {
					display: flex;
					align-items: center;

					.comment-like {
						display: flex;
						align-items: center;
						margin-right: 32rpx;
						cursor: pointer;

						.like-count {
							font-size: 22rpx;
							color: #666;
							margin-left: 8rpx;
						}
					}

					.reply-btn {
						font-size: 24rpx;
						color: #666;
						cursor: pointer;

						&:hover {
							color: #ff4757;
						}
					}
				}
			}
		}

		// 回复列表样式
		.reply-list {
			margin-left: 88rpx;
			border-left: 2rpx solid #f0f0f0;
			padding-left: 24rpx;
			margin-top: 16rpx;

			.reply-item {
				display: flex;
				margin-bottom: 24rpx;

				.reply-avatar {
					width: 48rpx;
					height: 48rpx;
					border-radius: 50%;
					margin-right: 16rpx;
					flex-shrink: 0;
				}

				.reply-content {
					flex: 1;

					.reply-header {
						display: flex;
						align-items: center;
						margin-bottom: 8rpx;

						.reply-user {
							font-size: 22rpx;
							color: #666;
							margin-right: 12rpx;
							font-weight: 500;
						}

						.reply-time {
							font-size: 20rpx;
							color: #999;
						}
					}

					.reply-text-wrapper {
						margin-bottom: 12rpx;

						.reply-target {
							font-size: 24rpx;
							color: #ff4757;
							margin-right: 8rpx;
						}

						.reply-text {
							font-size: 24rpx;
							color: #333;
							line-height: 1.4;
						}
					}

					.reply-actions {
						display: flex;
						align-items: center;

						.reply-like {
							display: flex;
							align-items: center;
							margin-right: 24rpx;
							cursor: pointer;

							.like-count {
								font-size: 20rpx;
								color: #666;
								margin-left: 6rpx;
							}
						}

						.reply-btn {
							font-size: 22rpx;
							color: #666;
							cursor: pointer;

							&:hover {
								color: #ff4757;
							}
						}
					}
				}
			}

			.more-replies {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 16rpx 0;
				color: #666;
				font-size: 24rpx;
				cursor: pointer;
				border-radius: 8rpx;

				&:hover {
					background-color: #f8f8f8;
					color: #ff4757;
				}

				.more-replies-text {
					margin-right: 8rpx;
				}
			}
		}

		.load-more-comments {
			text-align: center;
			padding: 24rpx 0;
			color: #666;
			font-size: 26rpx;
			cursor: pointer;

			&:hover {
				color: #ff4757;
			}
		}

		.empty-comments {
			text-align: center;
			padding: 80rpx 0;

			.empty-text {
				color: #999;
				font-size: 26rpx;
			}
		}

		.loading-comments {
			text-align: center;
			padding: 40rpx 0;

			.loading-text {
				color: #999;
				font-size: 26rpx;
			}
		}
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}
</style>